package com.woodws.fresh.im.rsocket

import com.woodws.fresh.im.api.dto.ImSessionDto
import com.woodws.fresh.im.api.service.ImSessionService
import com.woodws.fresh.im.controller.ConnectController
import org.springframework.messaging.rsocket.RSocketRequester
import org.springframework.stereotype.Component

@Component
class UserClient(val imSessionService: ImSessionService) {
    companion object{
        val CLIENTS: MutableMap<String, RSocketRequester> = mutableMapOf()
    }

    fun login(requester: RSocketRequester, session: ImSessionDto){
        session.server = "1"
        requester.rsocket()!!
            .onClose()
            .doFirst {

                // Add all new clients to a client list
                log.info("Client: {} CONNECTED.", session.userId)
                imSessionService.save(session)
                ConnectController.CLIENTS[session.userId.toString()] = requester
            }
            .doOnError {
                // Warn when channels are closed by clients
                log.warn("Channel to client {} CLOSED", session.userId)
            }
            .doFinally {
                // Remove disconnected clients from the client list
                imSessionService.deleteByUserId(session.userId!!)
                ConnectController.CLIENTS.remove(session.userId.toString())
                log.info("Client {} DISCONNECTED", session)
            }
            .subscribe()
    }
}